import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'
/*
注释mock,因为我们的数据来自数据库
import Mock from './mock'
Mock.bootstrap();*/
import 'font-awesome/css/font-awesome.min.css'
/*引入axios*/
import axios from 'axios'
//配置axios的全局基本路径
axios.defaults.baseURL='http://localhost:8080/'
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
  routes
})

//1 使用axios前置拦截器，让所有的请求都携带token
axios.interceptors.request.use(res=>{
  let token = localStorage.getItem("token");
  if(token){
    //携带token到请求头
    res.headers["token"] = token;
  }
  return res;
},error => {
  Promise.reject(error)
})


//2 使用axios后置拦截器，处理没有登录请求
axios.interceptors.response.use(res => {
  if ("noLogin" === res.data.message) {//后端响应的是没有登录的信息
    localStorage.removeItem("token");
    localStorage.removeItem("loginInfo");
    //跳转到登陆页面
    router.push({path: '/login'});
  }
  return res;
},error => {
  Promise.reject(error)
})



//3.静态资源拦截器/前端路由拦截器 - 拦截直接访问页面的请求
router.beforeEach((to, from, next) => {
  //访问登陆和注册页面就访问 - 登陆和注册页面本来就不需要登陆
  if (to.path == '/login' || to.path == "/shopRegister") {
    localStorage.removeItem('token');
    localStorage.removeItem('loginInfo');
    next();//放行
  }else{
    let loginInfo= localStorage.getItem('loginInfo');
    if (loginInfo) {
      next();
    } else {
      next({path: '/login'});//跳转到login
    }
  }
})


new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

